﻿using System.Collections.Generic;

namespace IdentityAtRest.Utility.Identity.Authorization
{
    public class AuthorizationManager : IAuthorizationManager
    {
        private readonly IPermissionPolicyRepository _permissionsRepository;

        public AuthorizationManager(IPermissionPolicyRepository permissionsRepository)
        {
            _permissionsRepository = permissionsRepository;
        }

        public IList<IAuthorizationDecision> Authorize(IList<IClaim> userClaims, params string[] requestedPermissions)
        {
            var authorizations = new List<IAuthorizationDecision>();

            IList<IPermissionPolicy> policies =
                _permissionsRepository.GetPermissionPolicies(requestedPermissions);
            if (policies != null)
            {
                foreach (IPermissionPolicy policy in policies)
                    authorizations.Add(policy.Authorize(userClaims));
            }

            return authorizations;
            
        }

        public bool IsAuthorized(IList<IClaim> userClaims, params string[] requestedPermissions)
        {
            return Authorize(userClaims, requestedPermissions).IsAuthorizedForAny();
        }

        protected IPermissionPolicyRepository PermissionPolicyRepository
        {
            get { return _permissionsRepository; }
        }
    }
}
